package com.tanhua.dubbo.api;

import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * @author ck
 * @date 2021/11/18 19:06
 */

@DubboService
public class VideoLikeApiImpl implements VideoLikeApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    //判断是否已经喜欢
    @Override
    public Boolean hasLiked(Long userId, Long vUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("vUserId").is(vUserId));
        return mongoTemplate.exists(query, VideoLike.class);
    }


    @Override
    public void save(VideoLike videoLike) {
        Query query = Query.query(Criteria.where("vid").is(videoLike.getVid()));
        Update update = new Update();
        update.inc("likeCount",1);
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true); //获取更新后的最新数据
        mongoTemplate.findAndModify(query, update, options, Video.class);

        mongoTemplate.save(videoLike);
    }

    @Override
    public VideoLike find(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.findOne(query,VideoLike.class);
    }

    @Override
    public void delete(VideoLike videoLike) {
        Query query = Query.query(Criteria.where("vid").is(videoLike.getVid()));
        Update update = new Update();
        update.inc("likeCount",-1);
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true); //获取更新后的最新数据
        mongoTemplate.findAndModify(query, update, options, Video.class);


        mongoTemplate.remove(videoLike);
    }
}
